#!/usr/bin/env python
# -*- utf-8 -*-
__software__ = 'newzBrowser'
__version__ = '0.1.0'
__author__ = 'Franck Tabary <franck34@sourceforge.net>'
__copyright__ = 'Copyright (c) 2006 Franck TABARY'
__license__ = """
 Copyright (C) 2006 Franck TABARY <franck34@sourceforge.net>

 newzBrowser is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License as
 published by the Free Software Foundation; either version 2 of
 the License, or (at your option) any later version.

 newzBrowser is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA."""

import os.path
import sys
import wx
import wx.grid
import wx.html
import cStringIO

import lib.PyAUI.PyAUI as PyAUI

ID_CreateTree = wx.ID_HIGHEST+1
ID_CreateGrid = ID_CreateTree+2
ID_Settings = ID_CreateTree+21
ID_About = ID_CreateTree+22
ID_FirstPerspective = ID_CreateTree+11+1000

# http://xoomer.alice.it/infinity77/eng/index3.html

#----------------------------------------------------------------------
def GetMondrianData():
    return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00 \x00\x00\x00 \x08\x06\x00\
\x00\x00szz\xf4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\x00qID\
ATX\x85\xed\xd6;\n\x800\x10E\xd1{\xc5\x8d\xb9r\x97\x16\x0b\xad$\x8a\x82:\x16\
o\xda\x84pB2\x1f\x81Fa\x8c\x9c\x08\x04Z{\xcf\xa72\xbcv\xfa\xc5\x08 \x80r\x80\
\xfc\xa2\x0e\x1c\xe4\xba\xfaX\x1d\xd0\xde]S\x07\x02\xd8>\xe1wa-`\x9fQ\xe9\
\x86\x01\x04\x10\x00\\(Dk\x1b-\x04\xdc\x1d\x07\x14\x98;\x0bS\x7f\x7f\xf9\x13\
\x04\x10@\xf9X\xbe\x00\xc9 \x14K\xc1<={\x00\x00\x00\x00IEND\xaeB`\x82' 


def GetMondrianBitmap():
    return wx.BitmapFromImage(GetMondrianImage())

def GetMondrianImage():
    stream = cStringIO.StringIO(GetMondrianData())
    return wx.ImageFromStream(stream)

def GetMondrianIcon():
    icon = wx.EmptyIcon()
    icon.CopyFromBitmap(GetMondrianBitmap())
    return icon


class PyAUIFrame(wx.Frame):
    
    def __init__(self, parent, id=-1, title="", pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE |
                                            wx.SUNKEN_BORDER |
                                            wx.CLIP_CHILDREN):

        wx.Frame.__init__(self, parent, id, title, pos, size, style)
        
        # tell FrameManager to manage this frame        
        self._mgr = PyAUI.FrameManager()
        self._mgr.SetFrame(self)
        
        self._perspectives = []
        self.n = 0
        self.x = 0
        
        self.SetIcon(GetMondrianIcon())

        # create menu
        mb = wx.MenuBar()

        file_menu = wx.Menu()
        file_menu.Append(wx.ID_EXIT, "Exit")
           
        options_menu = wx.Menu()
        options_menu.Append(ID_Settings, "Settings")

        help_menu = wx.Menu()
        help_menu.Append(ID_About, "About...")
        
        mb.Append(file_menu, "File")
        mb.Append(options_menu, "Options")
        mb.Append(help_menu, "Help")
        
        self.SetMenuBar(mb)

        self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
        self.statusbar.SetStatusWidths([-2, -3])
        self.statusbar.SetStatusText("Ready", 0)
        self.statusbar.SetStatusText("Welcome To "+__software__, 1)

        # min size for the frame itself isn't completely done.
        # see the end up FrameManager::Update() for the test
        # code. For now, just hard code a frame minimum size
        self.SetMinSize(wx.Size(400, 300))

        # create some toolbars
        #tb = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
        #tb.SetToolBitmapSize(wx.Size(16,16))
        #tb_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16))
        #tb.AddLabelTool(101, "Test", tb_bmp1)
        #tb.AddSeparator()
        #tb.AddLabelTool(101, "Test", tb_bmp1)
        #tb.Realize()
       
        # add a bunch of panes
        self._mgr.AddPane(self.CreateTreeCtrl(), PyAUI.PaneInfo().
                          Name("test8").CaptionVisible(False).
                          BestSize(wx.Size(200,)).
                          Left())

        self._mgr.AddPane(self.CreateGrid(), PyAUI.PaneInfo().
                          Name("Test").Caption("Grid").
                          Center().FloatingPosition(self.GetStartPosition()).
                          FloatingSize(wx.Size(300, 200)).Hide())
                                      
        self._mgr.AddPane(SettingsPanel(self, self), PyAUI.PaneInfo().
                          Name("settings").Caption("Dock Manager Settings").
                          Float().Hide())

        # add the toolbars to the manager
        #self._mgr.AddPane(tb, PyAUI.PaneInfo().
        #                  Name("tb").Caption("Toolbar").
        #                  ToolbarPane().Top().
        #                  LeftDockable(False).RightDockable(False))

        # "commit" all changes made to FrameManager   
        self._mgr.Update()
        
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        
        self.Bind(wx.EVT_MENU, self.OnSettings, id=ID_Settings)
        self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)
        self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_About)

    def OnClose(self, event):
        self._mgr.UnInit()
        self.Destroy()
        event.Skip()        


    def OnAbout(self, event):
        msg = __software__+' '+__version__+"\n\n" + \
              "Author: "+__author__+"\n\n" + \
              "Please Report Any Bug/Requests Of Improvements\n" + \
              "To Me At The Following Adresses:\n\n" + \
              "franck34@sourceforge.net\n\n" + \
              "Thanks to WingIDE, efficiant python editor.\n" + \
              "Based On pyAUI, wxPython, and ... " + \
              "Python" + wx.VERSION_STRING + "!!"
              
        dlg = wx.MessageDialog(self, msg, __software__+' '+__version__,
                               wx.OK | wx.ICON_INFORMATION)
        dlg.ShowModal()
        dlg.Destroy()        


    def GetDockArt(self):
        return self._mgr.GetArtProvider()

    def DoUpdate(self):
        self._mgr.Update()

    def OnEraseBackground(self, event):
        event.Skip()

    def OnSize(self, event):
        event.Skip()

    def OnSettings(self, event):
        # show the settings pane, and float it
        floating_pane = self._mgr.GetPane("settings").Float().Show()

        if floating_pane.floating_pos == wx.DefaultPosition:
            floating_pane.FloatingPosition(self.GetStartPosition())

        self._mgr.Update()

    def GetStartPosition(self):

        self.x = self.x + 20
        x = self.x
        pt = self.ClientToScreen(wx.Point(0, 0))
        
        return wx.Point(pt.x + x, pt.y + x)

    def OnChangeContentPane(self, event):
        self._mgr.Update()

    def CreateGrid(self):
        grid = wx.grid.Grid(self, -1, wx.Point(0, 0), wx.Size(150, 250), wx.NO_BORDER | wx.WANTS_CHARS)
        grid.CreateGrid(50, 20)
        return grid

    def CreateTreeCtrl(self):
        list_accounts=['Astraweb']
        list_groups=['alt.binaries.dvd.french','comp.lang.python']
        tree = wx.TreeCtrl(self, -1, wx.Point(0, 0), wx.Size(160, 250),
                           wx.TR_DEFAULT_STYLE | wx.NO_BORDER | wx.TR_HIDE_ROOT)
        
        root = tree.AddRoot("Accounts",0) # Account is hidden        
        items_account = []
        
        imglist = wx.ImageList(16, 16, True, 2)
        imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER, wx.ART_OTHER, wx.Size(16,16)))
        imglist.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16,16)))
        tree.AssignImageList(imglist)

        for account in list_accounts:
            id_account=tree.AppendItem(root, account, 0)
            for group in list_groups:
                id_group=tree.AppendItem(id_account,group,0)
                tree.AppendItem(id_group, "Search", 1)
            tree.Expand(id_account)
        
        tree.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.tree=tree
        return tree

    def OnRightDown(self,event):
        # Get position of clicked item
        pt = event.GetPosition();
        item, flags = self.tree.HitTest(pt)
        (x,y)=pt
        # Adjust position to display menu, only if pane Caption visible
        # x = event.GetX()        
        # y = event.GetY()+40
        

        level=0
        if flags != wx.TREE_HITTEST_NOWHERE:
            level=1
            # Click on an item
            self.tree.SelectItem(item)
            itemParent=self.tree.GetItemParent(item)
            
            # Detect level on a clicked item
            # root           = 0
            #   - item       = 1
            #      - subitem = 2
            # TODO: is there a better way to do that ??
            
            try:
                itemParent2=self.tree.GetItemParent(itemParent)
                level=level+1
            except:
                pass
                
            if level==2:
                try:
                    itemParent3=self.tree.GetItemParent(itemParent2)
                    level=level+1
                except:
                    pass
                
            if level==3:
                try:
                    itemParent4=self.tree.GetItemParent(itemParent3)
                    level=level+1
                except:
                    pass
                
        if level==0:
            self.PopupMenu(PopupMenuAddAccount('AddAccount'), (x,y))                      
        elif level==2:
            self.PopupMenu(PopupMenuAddGroup('AddGroup'), (x,y))
        elif level==3:
            self.PopupMenu(PopupMenuGroup('Group'), (x,y))

        
class PopupMenuAddAccount(wx.Menu):
    def __init__(self, WinName):
        wx.Menu.__init__(self)

        self.WinName = WinName
    
        item = wx.MenuItem(self, wx.NewId(), "Add an account")
        self.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnAddAccount, item)

    def OnAddAccount(self, event):
        print "Add Account: in the %s window" % self.WinName

class PopupMenuAddGroup(wx.Menu):
    def __init__(self, WinName):
        wx.Menu.__init__(self)

        self.WinName = WinName
    
        item = wx.MenuItem(self, wx.NewId(), "Add a group")
        self.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnAddGroup, item)

    def OnAddGroup(self, event):
        print "Add Group: in the %s window" % self.WinName

class PopupMenuGroup(wx.Menu):
    def __init__(self, WinName):
        wx.Menu.__init__(self)
        self.WinName = WinName
    
        item = wx.MenuItem(self, wx.NewId(), "Download new messages")
        self.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnDownloadNewMessages, item)
        item = wx.MenuItem(self, wx.NewId(), "Download all messages")
        self.AppendItem(item)
        self.Bind(wx.EVT_MENU, self.OnDownloadAllMessages, item)

    def OnDownloadNewMessages(self, event):
        print "Download New Messages"
        
    def OnDownloadAllMessages(self, event):
        print "Download All Messages"        
        
class SettingsPanel(wx.Panel):
    
    def __init__(self, parent, frame):
        wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition,wx.DefaultSize)
        self._frame = frame
        

def main():

    app = wx.PySimpleApp()
    
    frame = PyAUIFrame(None, wx.ID_ANY, __software__, wx.DefaultPosition, 
                       wx.Size(750, 590))

    frame.CenterOnScreen()    
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()


if __name__ == "__main__":
    main()

